package controller;

import com.jhlabs.image.*;
import entity.*;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import service.*;
import utils.ImageProcessor;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping(value = "/main", produces = "text/html;charset=utf-8")
public class DataHelperController {

    @Autowired
    private PatientService patientService;
    @Autowired
    private EvaluationService evaluationService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private LogService logService;
    @Autowired
    private ProjectsService projectsService;
    @Autowired
    private UserService userService;
    @Autowired
    private PatientsInfoService patientsInfoService;

    @Autowired
    private ExperimentDataService experimentDataService;

    private final static String SRC_PIC_PATH = "./src.jpg";
    private final static String DST_PIC_PATH = "dst.jpg";

    //病历CURD
    @ResponseBody
    @RequestMapping(value = "/getPatients.do", method = RequestMethod.GET)
    public String getPatients() {
        System.out.println("start fetch patient data...");
        JSONArray jsonArray = new JSONArray();

        List patients = patientService.findAll();
        for (Object obj : patients
                ) {
            Patient p = (Patient) obj;
            JSONObject json = new JSONObject();
            json.put("id", p.getId());
            json.put("pid", p.getPid());
            json.put("name", p.getName());
            json.put("address", p.getAddress());
            json.put("hid", p.getHid());
            json.put("birthday", p.getBirthday());
            json.put("nVisit", p.getnVisit());
            json.put("sex", p.getSex());

            jsonArray.put(json);
        }

        System.out.println(jsonArray.toString());

        return jsonArray.toString();
    }

    @ResponseBody
    @RequestMapping(value = "/deletePatient.do", method = RequestMethod.POST)
    public void deletePatient(HttpServletRequest request) {
        Integer id = Integer.parseInt(request.getParameter("id"));

        System.out.println(id);

        patientService.delete(id);
    }

    @ResponseBody
    @RequestMapping(value = "/addPatient.do", method = RequestMethod.POST)
    public String addPatient(HttpServletRequest request) {
        Integer id = Integer.parseInt(request.getParameter("id"));
        System.out.println("当前id为" + id);
        int pid = Integer.parseInt(request.getParameter("pid"));
        String name = request.getParameter("name");
        String address = request.getParameter("address");
        String birthday = request.getParameter("birthday");
        int hid = Integer.parseInt(request.getParameter("hid"));
        String sex = request.getParameter("sex");
        int nVisit = Integer.parseInt(request.getParameter("nVisit"));

        Patient p = new Patient();
        p.setPid(pid);
        p.setName(name);
        p.setAddress(address);
        p.setBirthday(birthday);
        p.setHid(hid);
        p.setSex(sex);
        p.setnVisit(nVisit);

        if (id == -1) {
            return patientService.save(p).toString();
        } else {
            p.setId(id);
            return patientService.update(p).toString();
        }

    }

    //获取统计图数据
    @ResponseBody
    @RequestMapping(value = "/getChartsData.do", method = RequestMethod.GET)
    public String getChartsData() {
        int[] sexDistribution = new int[]{0, 0};
        int[] nVisitDistrubution = new int[]{0, 0, 0, 0, 0};
        List patients = patientService.findAll();
        for (Object obj : patients
                ) {
            Patient p = (Patient) obj;
            if (p.getSex().equals("男")) {
                sexDistribution[0]++;
            } else {
                sexDistribution[1]++;
            }
            if (p.getnVisit() < 2) {
                nVisitDistrubution[0]++;
            } else if (p.getnVisit() < 6) {
                nVisitDistrubution[1]++;
            } else if (p.getnVisit() < 11) {
                nVisitDistrubution[2]++;
            } else if (p.getnVisit() < 16) {
                nVisitDistrubution[3]++;
            } else {
                nVisitDistrubution[4]++;
            }
        }

        JSONObject json = new JSONObject();
        json.put("male", sexDistribution[0]);
        json.put("female", sexDistribution[1]);
        JSONArray jsonArray = new JSONArray(nVisitDistrubution);
        json.put("nVisit", jsonArray);

        System.out.println(json.toString());
        return json.toString();
    }

    //评价体系CURD
    @ResponseBody
    @RequestMapping(value = "/addComment.do", method = RequestMethod.POST)
    public String addComment(HttpServletRequest request) {
        Integer id = Integer.valueOf(request.getParameter("id"));
        String name = request.getParameter("name");
        String detail = request.getParameter("detail");

        System.out.println(name);
        System.out.println(detail);

        Evaluation evaluation = new Evaluation();
        evaluation.setName(name);
        evaluation.setDescription(detail);

        if (id == -1)
            return evaluationService.save(evaluation).toString();
        else {
            evaluation.setId(id);
            return evaluationService.update(evaluation).toString();
        }
    }

    @ResponseBody
    @RequestMapping(value = "/getComments.do", method = RequestMethod.GET)
    public String getComments() {
        JSONArray jsonArray = new JSONArray();

        List evaluations = evaluationService.findAll();
        for (Object obj : evaluations
                ) {
            Evaluation e = (Evaluation) obj;
            JSONObject json = new JSONObject();
            json.put("id", e.getId());
            json.put("name", e.getName());
            json.put("detail", e.getDescription());

            jsonArray.put(json);
        }

        System.out.println(jsonArray.toString());

        return jsonArray.toString();
    }

    @ResponseBody
    @RequestMapping(value = "/deleteComment.do", method = RequestMethod.POST)
    public void deleteComment(HttpServletRequest request) {
        Integer id = Integer.parseInt(request.getParameter("id"));

        System.out.println(id);

        evaluationService.delete(id);
    }

    //项目管理CURD
    @ResponseBody
    @RequestMapping(value = "/addProject.do", method = RequestMethod.POST)
    public String addProject(HttpServletRequest request) {
        Integer id = Integer.valueOf(request.getParameter("id"));
        String date = request.getParameter("date");
        String content = request.getParameter("content");
        String member = request.getParameter("member");
        String target = request.getParameter("target");
        String progress = request.getParameter("progress");
        String achievement = request.getParameter("achievement");

        Projects pj = new Projects();
        pj.setDate(date);
        pj.setContent(content);
        pj.setMember(member);
        pj.setTarget(target);
        pj.setProgress(progress);
        pj.setAchievement(achievement);

        if (id == -1)
            return projectsService.save(pj).toString();
        else {
            pj.setId(id);
            return projectsService.update(pj).toString();
        }
    }

    @ResponseBody
    @RequestMapping(value = "/getProjects.do", method = RequestMethod.GET)
    public String getProjects() {
        JSONArray jsonArray = new JSONArray();

        List projects = projectsService.findAll();
        for (Object obj : projects
                ) {
            Projects pj = (Projects) obj;
            JSONObject json = new JSONObject();
            json.put("id", pj.getId());
            json.put("date", pj.getDate());
            json.put("content", pj.getContent());
            json.put("member", pj.getMember());
            json.put("target", pj.getTarget());
            json.put("progress", pj.getProgress());
            json.put("achievement", pj.getAchievement());

            jsonArray.put(json);
        }

        System.out.println(jsonArray.toString());

        return jsonArray.toString();
    }

    @ResponseBody
    @RequestMapping(value = "/deleteProject.do", method = RequestMethod.POST)
    public void deleteProject(HttpServletRequest request) {
        Integer id = Integer.parseInt(request.getParameter("id"));

        System.out.println(id);

        projectsService.delete(id);
    }

    //平台耗材CURD
    @ResponseBody
    @RequestMapping(value = "/addGoods.do", method = RequestMethod.POST)
    public String addGoods(HttpServletRequest request) {
        Integer id = Integer.valueOf(request.getParameter("id"));
        int gid = Integer.parseInt(request.getParameter("gid"));
        String gname = request.getParameter("gname");
        String gunit = request.getParameter("gunit");
        int gnumber = Integer.parseInt(request.getParameter("gnumber"));

        Goods goods = new Goods();
        goods.setGid(gid);
        goods.setGname(gname);
        goods.setGunit(gunit);
        goods.setGnumber(gnumber);
        if (id == -1)
            return goodsService.save(goods).toString();
        else {
            goods.setId(id);
            return goodsService.update(goods).toString();
        }
    }

    @ResponseBody
    @RequestMapping(value = "/getGoods.do", method = RequestMethod.GET)
    public String getGoods() {
        JSONArray jsonArray = new JSONArray();

        List goods = goodsService.findAll();
        for (Object obj : goods
                ) {
            Goods g = (Goods) obj;
            JSONObject json = new JSONObject();
            json.put("id", g.getId());
            json.put("gid", g.getGid());
            json.put("gname", g.getGname());
            json.put("gunit", g.getGunit());
            json.put("gnumber", g.getGnumber());

            jsonArray.put(json);
        }

        System.out.println(jsonArray.toString());

        return jsonArray.toString();
    }

    @ResponseBody
    @RequestMapping(value = "/deleteGoods.do", method = RequestMethod.POST)
    public void deleteGoods(HttpServletRequest request) {
        Integer id = Integer.parseInt(request.getParameter("id"));

        System.out.println(id);

        goodsService.delete(id);
    }

    //用户CURD
    @ResponseBody
    @RequestMapping(value = "/addUser.do", method = RequestMethod.POST)
    public String addUser(HttpServletRequest request) {
        Integer id = Integer.valueOf(request.getParameter("id"));
        String user = request.getParameter("user");
        String pwd = request.getParameter("pwd");
        int role = Integer.parseInt(request.getParameter("role"));

        if (role != 1 && role != 2)
            return "error";

        User u = new User();
        u.setUser(user);
        u.setPwd(pwd);
        u.setRole(role);

        if (id == -1)
            return userService.save(u).toString();
        else {
            u.setId(id);
            return userService.update(u).toString();
        }
    }

    @ResponseBody
    @RequestMapping(value = "/getUsers.do", method = RequestMethod.GET)
    public String getUsers() {
        JSONArray jsonArray = new JSONArray();

        List users = userService.findAll();
        for (Object obj : users
                ) {
            User user = (User) obj;
            JSONObject json = new JSONObject();
            json.put("id", user.getId());
            json.put("user", user.getUser());
            json.put("pwd", user.getPwd());
            json.put("role", user.getRole());

            jsonArray.put(json);
        }

        System.out.println(jsonArray.toString());

        return jsonArray.toString();
    }

    @ResponseBody
    @RequestMapping(value = "/deleteUser.do", method = RequestMethod.POST)
    public void deleteUser(HttpServletRequest request) {
        Integer id = Integer.parseInt(request.getParameter("id"));

        System.out.println(id);

        userService.delete(id);
    }

    //平台日志
    @ResponseBody
    @RequestMapping(value = "/getLogs.do", method = RequestMethod.GET)
    public String getLogs() {
        JSONArray jsonArray = new JSONArray();

        List logs = logService.findAll();
        for (Object obj : logs
                ) {
            Log log = (Log) obj;
            JSONObject json = new JSONObject();
            json.put("id", log.getId());
            json.put("user", log.getUser());
            json.put("date", log.getLoginDate());
            json.put("visitedPage", log.getVisitedPage());

            jsonArray.put(json);
        }

        System.out.println(jsonArray.toString());

        return jsonArray.toString();
    }

    //病人信息管理CURD
    @ResponseBody
    @RequestMapping(value = "/getPatientsInfo.do", method = RequestMethod.GET)
    public String getPatientsInfo() {
        JSONArray jsonArray = new JSONArray();

        List infos = patientsInfoService.findAll();
        for (Object obj : infos
                ) {
            PatientsInfo info = (PatientsInfo) obj;
            JSONObject json = new JSONObject();
            json.put("id", info.getId());
            json.put("name", info.getName());
            json.put("age", info.getAge());
            json.put("phone", info.getPhone());

            jsonArray.put(json);
        }

        System.out.println(jsonArray.toString());

        return jsonArray.toString();
    }

    @ResponseBody
    @RequestMapping(value = "/deletePatientsInfo.do", method = RequestMethod.POST)
    public void deletePatientsInfo(HttpServletRequest request) {
        Integer id = Integer.parseInt(request.getParameter("id"));

        System.out.println(id);

        patientsInfoService.delete(id);
    }

    @ResponseBody
    @RequestMapping(value = "/addPatientsInfo.do", method = RequestMethod.POST)
    public String addPatientsInfo(HttpServletRequest request) {
        Integer id = Integer.valueOf(request.getParameter("id"));

        String name = request.getParameter("name");
        int age = Integer.parseInt(request.getParameter("age"));
        String phone = request.getParameter("phone");

        PatientsInfo p = new PatientsInfo();
        p.setName(name);
        p.setAge(age);
        p.setPhone(phone);

        if (id == -1)
            return patientsInfoService.save(p).toString();
        else {
            p.setId(id);
            return patientsInfoService.update(p).toString();
        }
    }

    @ResponseBody
    @RequestMapping(value = "/changePic.do", method = RequestMethod.POST)
    public String changePic(HttpServletRequest request) throws IOException {
        String src = ImageProcessor.getSrcImageStr(request.getParameter("imageStr"));

        //生成临时图片,保存在tomcat的bin目录下
        ImageProcessor.GenerateImage(src, SRC_PIC_PATH);

        BufferedImage src_pic = ImageIO.read(new File(SRC_PIC_PATH));

        ArrayList<String> paths = new ArrayList<String>();

        //灰显
        ImageIO.write(new GrayFilter().filter(src_pic, null), "jpeg", new File(GrayFilter.class.getName() + "_" + DST_PIC_PATH));
        paths.add(GrayFilter.class.getName() + "_" + DST_PIC_PATH);
        //铬化
        ImageIO.write(new ChromeFilter().filter(src_pic, null), "jpeg", new File(ChromeFilter.class.getName() + "_" + DST_PIC_PATH));
        paths.add(ChromeFilter.class.getName() + "_" + DST_PIC_PATH);

        ImageIO.write(new MaskFilter().filter(src_pic, null), "jpeg", new File(MaskFilter.class.getName() + "_" + DST_PIC_PATH));
        paths.add(MaskFilter.class.getName() + "_" + DST_PIC_PATH);

        ImageIO.write(new GrayscaleFilter().filter(src_pic, null), "jpeg", new File(GrayscaleFilter.class.getName() + "_" + DST_PIC_PATH));
        paths.add(GrayscaleFilter.class.getName() + "_" + DST_PIC_PATH);


        String[] dsts = new String[4];
        int i = 0;

        for (String p : paths
                ) {
            dsts[i++] = ImageProcessor.getDstImageStr(ImageProcessor.GetImageStr(p));
        }

        return new JSONArray(dsts).toString();
    }

    @ResponseBody
    @RequestMapping(value = "/createPic.do", method = RequestMethod.POST)
    public String createPic(HttpServletRequest request) throws IOException {
        String src = ImageProcessor.getSrcImageStr(request.getParameter("imageStr"));

        //生成临时图片,保存在tomcat的bin目录下
        ImageProcessor.GenerateImage(src, SRC_PIC_PATH);

        BufferedImage src_pic = ImageIO.read(new File(SRC_PIC_PATH));

        ArrayList<String> paths = new ArrayList<String>();

        ImageIO.write(new InvertAlphaFilter().filter(src_pic, null), "jpeg", new File(InvertAlphaFilter.class.getName() + "_" + DST_PIC_PATH));
        paths.add(InvertAlphaFilter.class.getName() + "_" + DST_PIC_PATH);

        ImageIO.write(new SolarizeFilter().filter(src_pic, null), "jpeg", new File(SolarizeFilter.class.getName() + "_" + DST_PIC_PATH));
        paths.add(SolarizeFilter.class.getName() + "_" + DST_PIC_PATH);

        ImageIO.write(new SwimFilter().filter(src_pic, null), "jpeg", new File(SwimFilter.class.getName() + "_" + DST_PIC_PATH));
        paths.add(SwimFilter.class.getName() + "_" + DST_PIC_PATH);

        ImageIO.write(new EmbossFilter().filter(src_pic, null), "jpeg", new File(EmbossFilter.class.getName() + "_" + DST_PIC_PATH));
        paths.add(EmbossFilter.class.getName() + "_" + DST_PIC_PATH);


        String[] dsts = new String[4];
        int i = 0;

        for (String p : paths
                ) {
            dsts[i++] = ImageProcessor.getDstImageStr(ImageProcessor.GetImageStr(p));
        }

        return new JSONArray(dsts).toString();
    }


    //成像数据获取
    @ResponseBody
    @RequestMapping(value = "/getImagingData.do", method = RequestMethod.GET)
    public String getImagingData() {
        JSONArray jsonArray = new JSONArray();

        List datas = experimentDataService.findAll();
        for (Object obj : datas
                ) {
            ExperimentData data = (ExperimentData) obj;
            JSONObject json = new JSONObject();
            json.put("id", data.getId());
            json.put("time", data.getDate());
            json.put("value", data.getValue());

            jsonArray.put(json);
        }

        System.out.println(jsonArray.toString());

        return jsonArray.toString();
    }

    @ResponseBody
    @RequestMapping(value = "/deleteImagingData.do", method = RequestMethod.POST)
    public void deleteImagingData(HttpServletRequest request) {
        Integer id = Integer.parseInt(request.getParameter("id"));

        System.out.println(id);

        experimentDataService.delete(id);
    }

    @ResponseBody
    @RequestMapping(value = "/addImagingData.do", method = RequestMethod.POST)
    public String addImagingData(HttpServletRequest request) {
        Integer id = Integer.valueOf(request.getParameter("id"));
        String date = request.getParameter("time");
        String value = request.getParameter("value");

        ExperimentData experimentData = new ExperimentData();
        experimentData.setDate(date);
        experimentData.setValue(value);

        if (id == -1)
            return experimentDataService.save(experimentData).toString();
        else {
            experimentData.setId(id);
            return experimentDataService.update(experimentData).toString();
        }
    }

    //    getRunNDT
    @ResponseBody
    @RequestMapping(value = "/getRunNDT.do", method = RequestMethod.GET)
    public String getRunNDT(HttpServletRequest request, HttpSession session) {
        String path = "C:\\runNDT.bat";
        Runtime run = Runtime.getRuntime();
        try {
            // run.exec("cmd /k shutdown -s -t 3600");
            Process process = run.exec("cmd.exe /k start " + path);
            InputStream in = process.getInputStream();
            while (in.read() != -1) {
                System.out.println(in.read());
            }
            in.close();
            process.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
        }


        System.out.println("success!");

        return null;
    }

}
